import os
import sys
from pathlib import Path
from importlib import import_module, util
import traceback

CURRENT_FILE_PATH = Path(__file__).resolve()
ROOT_PATH = CURRENT_FILE_PATH.parent
CORE_PATH = ROOT_PATH / "core"
LIBS_PATH = ROOT_PATH / "common/libs"
PUBLIC_MODULE_PATH = ROOT_PATH / "common/public_module"
SUB_PROCESS_PATH = ROOT_PATH / "sub_process"
print(LIBS_PATH)
for path in [CORE_PATH, LIBS_PATH, PUBLIC_MODULE_PATH, SUB_PROCESS_PATH]:
    if path.is_dir() and str(path) not in sys.path:
        sys.path.append(str(path))

printer = import_module("printer").IndentPrinter()

CONFIG = import_module("config")
SUB_PROCESS = CONFIG.SUB_PROCESS

os.environ["COMMON_PATH"] = str(ROOT_PATH / "common")
os.environ["DATA_PATH"] = str(CONFIG.DATA_PATH)


def main():
    printer("[主流程] 开始")
    try:
        for process in SUB_PROCESS:
            printer(f"[主流程] 子流程开始（{process["title"]}）")
            relative_path = process["path"]
            module_name = process["name"]
            full_module_path = os.path.join(
                SUB_PROCESS_PATH, relative_path, f"{module_name}.py"
            )

            if not os.path.exists(full_module_path):
                raise FileNotFoundError(f"模块文件不存在: {full_module_path}")

            spec = util.spec_from_file_location(module_name, full_module_path)
            if spec is None:
                raise ImportError(
                    f"无法加载模块: {module_name} 从路径: {full_module_path}"
                )
            module = util.module_from_spec(spec)
            spec.loader.exec_module(module)

            if hasattr(module, "main"):
                params = process.get("params", None)
                if params is not None:
                    module.main(**params)
                else:
                    module.main()
            else:
                raise AttributeError(f"模块 {process["title"]} 中未找到 main 函数")

            printer(f"[主流程] 子流程完成（{process["title"]}）")
        printer(f"[主流程] 👏 全部子流程完成，总耗时<run_time>。", run_time="hh:mm:ss")

    except Exception as e:
        printer(f"[主流程] 发生错误: {e}")
        printer("[主流程] 程序终止")
        for line in traceback.format_exc().splitlines():
            printer(line)  # 逐行打印调用栈
        return


if __name__ == "__main__":
    main()
